// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

// ReSharper disable CommentTypo
// ReSharper disable IdentifierTypo
// ReSharper disable LocalizableElement
// ReSharper disable StringLiteralTypo
// ReSharper disable UnusedParameter.Local

/* Startup.cs -- конфигурирование перед запуском приложения
 * Ars Magna project, http://arsmagna.ru
 */

#region Using directives

using AM.Web;

using Istu.OldModel;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;

#endregion

#nullable enable

namespace Restaurant;

/// <summary>
/// Конфигурирование перед запуском приложения.
/// </summary>
public class Startup
{
    /// <summary>
    /// Конструктор.
    /// </summary>
    public Startup
        (
            IConfiguration configuration
        )
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices
        (
            IServiceCollection services
        )
    {
        services.AddSingleton (Configuration);

        services.AddOldModel();

        services.AddControllers();
        services.AddSwaggerGen (c =>
        {
            c.SwaggerDoc ("v1", new OpenApiInfo { Title = "Restaurant", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure
        (
            IApplicationBuilder app,
            IWebHostEnvironment env
        )
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI (c => c.SwaggerEndpoint ("/swagger/v1/swagger.json", "Restaurant v1"));
        }

        app.UseHttpsRedirection();

        app.UseCors (options => { options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); });
        app.UseRouting();

        app.UseAuthorization();

        var allowedAddresses = Configuration["AllowedIP"];
        if (!string.IsNullOrEmpty (allowedAddresses))
        {
            // пустая строка означает, что фильтрация по IP-адресам не нужна
            app.UseMiddleware<SecureAccessMiddleware> (allowedAddresses);
        }

        app.UseEndpoints (endpoints => { endpoints.MapControllers(); });
    }
}
